package outbound_account

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/dto/market"
	"git.myscrm.cn/golang/stark/v4"
	"gorm.io/gorm"
)

type outboundAccountRepository struct {
	tenant_db.TenantDB
}

func NewOutboundAccountRepository() OutboundAccountRepositoryIface {
	return &outboundAccountRepository{}
}

func (r *outboundAccountRepository) GetAccount(ctx context.Context, condition map[string]interface{}) (*GfyxOutboundBindPo, error) {
	var po GfyxOutboundBindPo
	db := r.GetTenantDB(ctx).Table(GfyxOutboundBindPo{}.TableName())
	condition["is_deleted"] = constants.IsDeletedFalse
	err := db.Where(condition).Find(&po).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		stark.Logger.Errorf(ctx, "repository-method:GetAccount, err:%v", err)
		return nil, err
	}
	return &po, nil
}

func (r *outboundAccountRepository) SaveAccount(ctx context.Context, po *GfyxOutboundBindPo) (int64, error) {
	result := r.GetTenantDB(ctx).Table(po.TableName()).Save(po)
	if result.Error != nil {
		stark.Logger.Errorf(ctx, "SaveAccount save data : %+v, error: %+v", po, result.Error)
		return 0, result.Error
	}
	return po.ID, nil
}

func (r *outboundAccountRepository) GetExpenseDetail(ctx context.Context) ([]*market.ExpenseDetail, error) {
	expenseDetailList := make([]*market.ExpenseDetail, 0)
	db := r.GetTenantDB(ctx)
	err := db.Raw(`
		select SUM(CEIL(duration / 60)) AS duration_minutes, date(end_time) as date, 0.6 as unit_price from gfyx_outbound_task_log where duration > 0 and is_deleted = 0 group by date order by date desc limit 20000
	`).Scan(&expenseDetailList).Error

	return expenseDetailList, err
}
